package org.folio.rest.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.folio.cql2pgjson.CQL2PgJSON;
import org.folio.cql2pgjson.exception.FieldException;
import org.folio.rest.impl.other.PartyUtil;
import org.folio.rest.impl.pojo.NotifyLogExcel;
import org.folio.rest.impl.util.FileExport;
import org.folio.rest.jaxrs.model.NotifyLog;
import org.folio.rest.jaxrs.model.NotifyLogCollection;
import org.folio.rest.jaxrs.model.NotifyLogGroup;
import org.folio.rest.jaxrs.resource.PartyNotifyLog;
import org.folio.rest.persist.PgUtil;
import org.folio.rest.persist.cql.CQLWrapper;
import org.folio.rest.tools.messages.Messages;
import org.folio.rest.tools.utils.ValidationHelper;

import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lee
 * @Classname NotifyLogImpl
 * @Description TODO
 * @Date 2020/6/18 16:39
 * @Created by lee
 */
public class NotifyLogImpl implements PartyNotifyLog {
    private final Logger logger = LoggerFactory.getLogger("modparty");
    private final Messages messages = Messages.getInstance();
    private static final String NOTIFY_TABLE = "notify_log";
    private CQLWrapper getCQL(String query, int limit, int offset) throws FieldException {
        return new CQLWrapper(new CQL2PgJSON(NOTIFY_TABLE + ".jsonb"), query, limit, offset);
    }

    @Override
    public void getPartyNotifyLog(String query, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        CQLWrapper cql = null;
        if (!StrUtil.isBlankOrUndefined(query) && !"()".equals(query)) {
            try {
                cql = PartyUtil.getCQL(query, limit, offset, NOTIFY_TABLE);
            } catch (Exception e) {
                ValidationHelper.handleError(e, asyncResultHandler);
                return;
            }
        }
        PgUtil.get(NOTIFY_TABLE, NotifyLog.class, NotifyLogCollection.class, cql == null ? null : cql.getQuery(), offset, limit, okapiHeaders, vertxContext, GetPartyNotifyLogResponse.class, asyncResultHandler);
    }


    @Override
    public void getPartyNotifyLogExportExcel(String query, int offset, int limit, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        CQLWrapper cql = null;
        if (!StrUtil.isBlankOrUndefined(query) && !"()".equals(query)) {
            try {
                cql = PartyUtil.getCQL(query, limit, offset, NOTIFY_TABLE);
            } catch (Exception e) {
                ValidationHelper.handleError(e, asyncResultHandler);
                return;
            }
        }
        Map<String,String> map = new LinkedHashMap<>();
        map.put("name","姓名");
        map.put("message","信息内容");
        map.put("sendDate","发送日期");
        map.put("notifyMode","通知方式\n(1:微信2:短信3:邮件)");
        map.put("accountType","账号类型\n(1:读者2:管理员");
        map.put("messageType","信息类型\n(1:报名成功2:报名失败3:审核通过4:审核失败)");
        map.put("phoneNumber","手机号码");
        map.put("userAccount","用户账号");
        map.put("partyName","活动名称");
        map.put("reserveChannel","报名渠道\n(1:微信2:web3:后台)");
        String[] fields = {"jsonb"};
        String fieldsStr = Arrays.toString(fields);
        PgUtil.postgresClient(vertxContext, okapiHeaders).get(NOTIFY_TABLE, NotifyLogGroup.class, fieldsStr.substring(1, fieldsStr.length() - 1), cql == null ? "" : cql.toString(),
                true, false, false,
                reply -> {
                    if (reply.succeeded()) {

                        List<NotifyLogExcel> list = reply.result().getResults().stream().map(a -> {
                            NotifyLogExcel notifyLogExcel = new NotifyLogExcel();
                            BeanUtil.copyProperties(a, notifyLogExcel);
                            return notifyLogExcel;
                        }).collect(Collectors.toList());
                        FileExport.fileExports(map, list, h -> {
                            if (h.succeeded()) {
                                asyncResultHandler.handle(Future.succeededFuture(GetPartyNotifyLogExportExcelResponse.respond200WithApplicationOctetStream(h.result())));
                            } else {
                                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                            }
                        });
                    } else {
                        ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                    }
                });
    }
 
}
